package com.happy_hao.msg.controller;

import com.happy_hao.msg.dto.NoPeriodStartRequest;
import com.happy_hao.msg.dto.PeriodicSendRequest;
import com.happy_hao.msg.dto.SystemInfoRequest;
import org.springframework.http.ResponseEntity;
import com.happy_hao.msg.common.Result;
import com.happy_hao.msg.dto.EmailRequest;
import com.happy_hao.msg.exception.ServiceException;
import com.happy_hao.msg.service.EmailService;
import com.happy_hao.msg.util.EmailUtil;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.validation.Valid;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.Date;

@RestController
@RequestMapping("/msg/email")
public class EmailController {

    @Resource
    private EmailUtil emailUtil;

    @Resource
    private EmailService emailService;

    @PostMapping("/instantSend")
    public Result instantSend(@Valid @RequestBody EmailRequest emailRequest) {
        try {
            emailService.instantSend(emailRequest);
        } catch (MessagingException | UnsupportedEncodingException e) {
            throw new ServiceException("邮件发送失败");
        }
        return Result.success();
    }

    @PutMapping("/newScheduledSend")
    public Result newScheduledSend(@Valid @RequestBody EmailRequest emailRequest) {
        if(emailRequest.getEndTime()==null){
            return Result.error().message("您输入的时间不合法");
        }
        Date now = new Date();
        if(emailRequest.getEndTime().before(now)){
            return Result.error().message("您输入的时间不合法");
        }
        emailService.newScheduledSend(emailRequest);
        return Result.success();
    }


    // 启动周期性发送
    @PostMapping("/periodicSend")
    public Result periodicSend(@RequestBody @Validated PeriodicSendRequest periodicSendRequest) {
        System.out.println("periodicSendRequest = " + periodicSendRequest);
        emailService.periodicSend(periodicSendRequest);
        return Result.success();
    }

    // 停止周期性发送
    @GetMapping("/stopPeriodicSend/{taskId}")
    public Result stopPeriodicSend(@PathVariable String taskId) {
        emailService.stopPeriodicSend(taskId);
        return Result.success();
    }

//非周期性发送
    @PostMapping("/noPeriodStart")
    public Result noPeriodStart(@RequestBody @Validated NoPeriodStartRequest noPeriodStartRequest) {
        emailService.startEmailTask(noPeriodStartRequest);
        return Result.success();
    }

//取消非周期性发送
    @GetMapping("/noPeriodsTop/{taskId}")
    public Result noPeriodsTop(@PathVariable String taskId) {
        emailService.cancelEmailTask(taskId);
        return Result.success();
    }

    @PostMapping("/systemInfo")
    public Result systemInfo(@RequestBody @Validated  SystemInfoRequest systemInfoRequest) {
        emailService.systemInfo(systemInfoRequest);
        return Result.success();
    }
}
